package com.lingyuan.product.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingyuan.product.domain.CategoryEntity;
import com.lingyuan.product.mapper.CategoryMapper;
import com.lingyuan.product.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName CategoryServiceImpl
 * @Description 描述
 * @Author guoxin
 * @Date 2024/9/18 15:37
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,CategoryEntity> implements CategoryService {
    /**
     * 功能: 获取分类树
     */
    @Override
    public List<CategoryEntity> categoryTree() {
        //先获取所有分类
        List<CategoryEntity> categoryList = this.list();
        //过滤掉 顶级分类
        List<CategoryEntity> collect = categoryList.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(categoryEntity -> {
                    categoryEntity.setChiledList(CategoryEntityTwo(categoryEntity.getCatId(), categoryList));
                    return categoryEntity;
                }).collect(Collectors.toList());
        return collect;
    }

    private List<CategoryEntity> CategoryEntityTwo(Long catId, List<CategoryEntity> categoryList) {
        List<CategoryEntity> collect = categoryList.stream().filter(categoryEntity -> categoryEntity.getParentCid().equals(catId))
                .map(categoryEntity -> {
                    categoryEntity.setChiledList(CategoryEntityTwo(categoryEntity.getCatId(), categoryList));
                    return categoryEntity;
                }).collect(Collectors.toList());
        return collect.size() == 0 ? null : collect;
    }
}
